package com.har.modules.web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.har.common.config.WxConfig;
import com.har.common.utils.StringUtil;
import com.har.modules.web.service.WeChatService;
import com.har.utils.http.HttpUtil;
import com.har.utils.string.RandomUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author maoruidd
 * @create 2018 - 08 - 03 - 上午 10:25
 */

@Slf4j
@Service
public class WeChatServiceImpl implements WeChatService {

    @Autowired
    private WxConfig wxConfig;

    @Override
    public String userAuthorize(JSONObject dataJson) {
        //用户授权调用的微信url
        String authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=APPID&redirect_uri=REDIRECTURI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        //微信回调url
        String RedirectUrl = wxConfig.getWxAuthCallBackUrl();
        //生成4位随机数
        String code=RandomUtils.generateNumberString(4);
        // 用户类型加用户id        1:企业 0:员工 1+1
        String state=dataJson.getString("type")+dataJson.getString("id");
        try {
            authUrl = authUrl.replace("APPID",wxConfig.getAppId());
            RedirectUrl= URLEncoder.encode(RedirectUrl,"UTF-8");
            authUrl = authUrl.replace("REDIRECTURI",RedirectUrl);
//            authUrl = authUrl.replace("code",code);
            authUrl = authUrl.replace("STATE",state);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        log.info("userAuthorizeUrl>>>{}",authUrl);

        return authUrl;
    }

    @Override
    public JSONObject callBack(String code, String state) throws Exception {

        if(!StringUtil.isEmpty(code)){

            //获取access_token
            String tokenResult=getAccessToken(code);

            JSONObject respJson=null;

            respJson=JSONObject.parseObject(tokenResult);
            //获取用户信息
            String userinfo=getUserinfo(respJson);

            if(!StringUtil.isEmpty(state)){

                JSONObject dataJson=new JSONObject();

                dataJson.put("userinfo",userinfo);

                dataJson.put("state",state);

                return dataJson;
            }

        }
        return null;
    }

    /**
     * 获取 Access_token
     * @return
     */
    private String getAccessToken(String code) {

        String tokenResult=null;

        //通过code换取网页授权access_token的url模板
        String accessTokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token" ;
        String reqParam = "appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        //替换code
        reqParam = reqParam.replace("CODE",code);
        reqParam = reqParam.replace("APPID",wxConfig.getAppId());
        reqParam = reqParam.replace("SECRET",wxConfig.getAppsecret());

        log.info("accessTokenUrl>>>{}",accessTokenUrl);

        //请求参数
        try {

            tokenResult = HttpUtil.get(accessTokenUrl,reqParam);

            log .info("AccessToken>>>{}",tokenResult);

            return tokenResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取用户信息
     * @param respJson
     * @return
     */
    private String getUserinfo(JSONObject respJson){
        //拉取用户信息url
        String userinfoUrl="https://api.weixin.qq.com/sns/userinfo";
        String reqParam = "access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

        reqParam = reqParam.replace("ACCESS_TOKEN",respJson.getString("access_token"));

        reqParam = reqParam.replace("OPENID",wxConfig.getAppId());
        log.info("userinfoUrl>>>{}",userinfoUrl);
        //请求参数
        String userResult=null;
        try {

            userResult=HttpUtil.get(userinfoUrl,reqParam);

            log.info("userResult>>>{}",userResult);

            return userResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
